import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class LocationNativeUtil {
  static const _methodChannelName = 'flutter.keqiang.com/location';

  static const _platformMethod = MethodChannel(_methodChannelName);

  /// 开启定位
  static Future<LocationResult?> startLocation() async {
    try {
      var result = await _platformMethod.invokeMethod('startLocation');
      return LocationResult(
          address: result['address'],
          longitude: result['longitude'],
          latitude: result['latitude']);
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
    return null;
  }

  /// 停止定位
  static void stopLocation() async {
    try {
      // 此处如果不执行await，则无法捕获异常
      await _platformMethod.invokeMethod('stopLocation');
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
  }

  /// 关闭定位，释放资源
  static void closeLocation() async {
    try {
      await _platformMethod.invokeMethod('closeLocation');
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
  }

  /// 是否永久拒绝定位权限
  ///
  /// 返回null则无法判断是否永久拒绝
  /// （一定要在权限申请的回调方法中调用才有效果）
  static Future<bool?> isPermanentDeniedLocationPermission() async {
    try {
      return await _platformMethod.invokeMethod('isPermanentDeniedLocationPermission');
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
    return null;
  }

  /// 打开设置定位权限界面
  ///
  /// 返回是否打开了定位权限，如果值为null，则无法判断是否打开定位权限。
  /// IOS由于无法获取是否从设置权限界面返回，所以始终返回null
  static Future<bool?> openSetLocationPermission() async {
    try {
      return await _platformMethod.invokeMethod('openSetLocationPermission');
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
    return null;
  }
}

/// 定位结果
class LocationResult {
  const LocationResult({this.address, this.longitude, this.latitude});

  /// 定位地址
  final String? address;

  /// 经度
  final double? longitude;

  /// 纬度
  final double? latitude;
}
